package com.itheima.controller;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.pojo.Setmeal;
import com.itheima.resources.*;
import com.itheima.service.OrderService;
import com.itheima.service.SetMealService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RequestMapping(value = "/order",name = "预约模块")
@RestController
public class OrderController {

    @Reference
    private SetMealService setMealService;

    @Autowired
    private JedisPool jedisPool;

    //todo:模拟降级处理 1.5秒以后跳转去OrderServiceMock类
    @Reference(mock = "com.itheima.service.impl.OrderServiceMock", timeout = 1500)
    private OrderService orderService;

    @RequestMapping(value = "/findSetMealById.do",name = "根据套餐id查询单个套餐信息")
    public Result findSetMealById(@RequestParam("id") String setMealId ){
        try {
            //查询套餐数据
            Setmeal setmeal = setMealService.findSetMealCommonById(setMealId);
            return new Result(true,"查询套餐成功",setmeal);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询套餐成功");
        }
    }

    @RequestMapping(value = "/SendVerifyCode.do",name = "发送验证码短信")
    public Result SendVerifyCode(@RequestParam("telephone") String telephone ){
        try {
            //产生4位数的验证码
            String code = String.valueOf(ValidateCodeUtils.generateValidateCode(4)) ;

            //将手机号作为key,验证码作为value存储到redis中,方便后台验证
            Jedis jedis = jedisPool.getResource();
            //存储到redis中,并设置存储时间 90秒.超过时间即失效
            jedis.setex(telephone+"_"+ RedisMessageConstant.SENDTYPE_ORDER,90,code);
            //释放jedis
            jedis.close();

            //发送短信
            SMSUtils.sendCode(telephone,code);
            //System.out.println("code = " + code);
            return new Result(true,"短信验证码发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "短信验证码发送失败");
        }
    }

    @RequestMapping(value = "/addOrder.do",name = "添加预约")
    public Result addOrder(@RequestBody Map map){
        try {
            Jedis jedis = jedisPool.getResource();
            //查询redis中存储的验证码
            String redisCode = jedis.get(map.get("telephone") + "_" + RedisMessageConstant.SENDTYPE_ORDER);
            //释放jedis
            jedis.close();

            //获取用户提交的验证码
            String code = (String) map.get("validateCode");

            if (redisCode==null){
                return new Result(false,"验证码已过时,请重新获取");
            }

            //比较验证码是否正确
            if (!redisCode.equals(code)){
                return new Result(false,"验证码错误");
            }

            //todo:支付需求添加代码:↓
            //获取16位唯一订单号
            String orderNum = OrderNumUtils.getOrderNumForString();

            String telephone = (String) map.get("telephone");
            //获取套餐id
            String setMealId = (String) map.get("setmealId");

            //获取套餐价格
            Integer totalPay = setMealService.findPriceBySetMealId(setMealId);

            //获取支付链接
            String code_url = PayUtils.createOrder(orderNum, totalPay);
            System.out.println("code_url = " + code_url);

            map.put("orderNum",orderNum);
            map.put("totalPay",totalPay);
            map.put("code_url",code_url);
            map.put("telephone",telephone);
            //todo:支付需求添加代码:↑



            //调用生产者添加预约订单
            Order order=orderService.addOrder(map);

            //todo:如果收到id为-1说明走了mock
            if (order.getId() == -1) {
                return new Result(false, "预约失败", order);
            } else {
                return new Result(true, "添加待支付订单成功", order);
            }

        } catch (RuntimeException e) {
            e.printStackTrace();
            //将报错信息返回回去
            return new Result(false,e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"预约失败");
        }
    }

    @RequestMapping(value = "/payNotify.do",method = RequestMethod.POST)
    public void PayNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.获取读入的流
        ServletInputStream inputStream = request.getInputStream();
        //2.将xml文件转换成java对象
        XmlMapper xmlMapper = new XmlMapper();
        Map paramMap = xmlMapper.readValue(inputStream, Map.class);
        // 3.调用orderService，修改订单状态
        orderService.updateState(paramMap);
        // 4.返回微信平台，接收成功
        HashMap<String, String> result = new HashMap<>();
        result.put("return_code", "SUCCESS");
        result.put("return_msg", "OK");
        // 将map转为xml
        String xml = xmlMapper.writeValueAsString(result);
        response.setContentType("application/xml;charset=utf-8");
        response.getWriter().write(xml);
    }

    @RequestMapping(value = "/findIsPaidByOrderId.do",name = "查询用户是否支付成功")
    public Result findIsPaidByOrderId(@RequestParam("oid") String orderId ){
        try {

            Order order = orderService.findIsPaidByOrderId(orderId);
            if (order.getIsPaid()==1){
                String telephone =(String)order.getTelephone();

                //产生4位数的验证码
                String code = String.valueOf(ValidateCodeUtils.generateValidateCode(4)) ;
                SMSUtils.sendCode(telephone,code);
            }
            if (order!= null){
                return new Result(true,"用户支付成功!",order);
            }else {
                return new Result(false,"无法查询用户订单!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "用户支付失败!");
        }
    }



    @RequestMapping(value = "/findOrderSuccess.do",name = "预约成功回显预约消息")
    public Result findOrderSuccess(@RequestParam("id") String id ){
        try {
            //查询数据
            Map map=orderService.orderSuccess(id);
            return new Result(true,"查询套餐成功",map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询套餐成功");
        }
    }
}
